<template>
  <el-dialog title="选择标签" width="60%" class="px-0" :visible.sync="dialogVisible" :before-close="handleClose">
    <div class="tag-select">
      <!-- 分类标签导航 -->
      <div class="tag-nav">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane v-for="tab in tabs" :key="tab.name" :label="tab.label" :name="tab.name">
            <template #label>
              <span>{{ tab.label }}</span>
              <el-badge v-if="getSelectedCountByTab(tab.name)" 
              :value="getSelectedCountByTab(tab.name)" :max="99" size="mini">                
              </el-badge>
              
            </template>
          </el-tab-pane>
        </el-tabs>

        <!-- 搜索框 -->
        <!-- <div class="search-box">
                    <el-input v-model="searchKeyword" placeholder="搜索全部标签" prefix-icon="el-icon-search" clearable
                        @input="handleSearch">
                    </el-input>
                </div> -->
      </div>

      <!-- 已选标签 -->
      <div v-show="selectedTags.length" class="flex-x justify-start items-center flex-wrap gap-4 pt-2 pb-4 border-b" >
        <span>已选标签 ({{ selectedTags.length }})</span>

        <el-tag v-for="tag in selectedTags" :key="tag.id" size="small" closable @close="removeTag(tag)">
          {{ tag.name }}
        </el-tag>
      </div>

      <!-- 标签表区域 -->
      <div class="tag-groups mt-4">
        <div v-for="group in parentTags" :key="group.id" class="tag-group">
          <div class="group-title">{{ group.name }}</div>
          <div class="group-tags">
            <el-tag v-for="tag in getLeafTags(group.id)" :key="tag.id" :type="isSelected(tag) ? 'primary' : 'info'"
              @click="toggleTag(tag)" :effect="isSelected(tag) ? 'dark' : 'plain'" size="small">
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
        <div class="group-tags">          
            <el-tag v-for="tag in nonParentTags" :key="tag.id" :type="isSelected(tag) ? 'primary' : 'info'"
              @click="toggleTag(tag)" :effect="isSelected(tag) ? 'dark' : 'plain'">
              {{ tag.name }}
            </el-tag>          
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import api from '@/common/api'
import utils from '@/common/utils'

const cachedGetTagClassification = utils.cachedCall(api.admin_getTagClassification, 30)
const cachedGetTagList = utils.cachedCall(api.admin_getTagList, 30)

export default {
  name: 'TagSelectDialog',
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      activeTab: '1',
      searchKeyword: '',
      tabs: [],
      selectedTags: [],
      dialogVisible: false,
      allTags: []
    }
  },
  computed: {
    currentGroupTags() {
      return this.allTags.filter(tag => tag.tcid === Number(this.activeTab))
    },
    parentTags() {
      // 顶层标签
      return this.currentGroupTags.filter(tag => !tag.isLeaf)
    },
    nonParentTags() {
      // 非顶层标签
      return this.currentGroupTags.filter(tag => tag.isLeaf && !tag.parentId)
    }
  },
  methods: {
    async fetchClassifications() {
      try {
        const { data } = await cachedGetTagClassification()
        this.tabs = data.data.map(item => ({
          name: String(item.id),
          label: item.name
        }))
        if (this.tabs.length) {
          this.activeTab = this.tabs[0].name
        }
      } catch (error) {
        this.$message.error('获取标签分类失败')
      }
    },
    async fetchTags() {
      try {
        const { data } = await cachedGetTagList() // query all tag        
        this.allTags = data.data
      } catch (error) {
        this.$message.error('获取标签列表失败')
      }
    },
    async handleTabClick(tab) {     
    },
    getLeafTags(parentId) {
      return this.currentGroupTags.filter(tag => tag.parentId === parentId)
    },
    handleSearch() {
      // 处理搜索
    },
    isSelected(tag) {
      return this.selectedTags.some(t => t.id === tag.id)
    },
    toggleTag(tag) {
      if (this.isSelected(tag)) {
        this.removeTag(tag)
      } else {
        this.selectedTags.push(tag)
      }      
    },
    removeTag(tag) {
      const index = this.selectedTags.findIndex(t => t.id === tag.id)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      }      
    },
    handleClose() {
      this.dialogVisible = false
      this.selectedTags = []
    },
    handleConfirm() {
      const tags = this.selectedTags.map(tag => tag)
      const tagIds = this.selectedTags.map(tag => tag.id)
      this.$emit('input', tagIds)
      this.$emit('change', tagIds, tags)
      this.dialogVisible = false
    },
    async open(tagIds = []) {
      this.dialogVisible = true
      await this.fetchClassifications()
      await this.fetchTags()     
      this.selectedTags = (tagIds || []).map(id => this.allTags.find(tag => tag.id === id))
    },
    getSelectedCountByTab(tabName) {
      return this.selectedTags.filter(it => 
        this.allTags.some(tag => tag.id === it.id && tag.tcid === Number(tabName))
      ).length
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding: 0 20px !important;
}

.tag-select {
  border: none;
  border-radius: 0;
}

.tag-nav {
  justify-content: space-between;
  align-items: center;
}

.search-box {
  width: 200px;
}

.selected-tags {
  padding: 10px 20px;
  border-bottom: 1px solid #EBEEF5;
}

.selected-header {
  margin-bottom: 10px;
  color: #606266;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-groups {
  min-height: 250px;
  max-height: 350px;
  overflow-y: auto;
}

.tag-group {
  margin-bottom: 20px;
}

.group-title {
  margin-bottom: 10px;
  color: #606266;
}

.group-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.el-tag {
  cursor: pointer;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}
</style>